import operate from '@feidao/web/atom/nodejs/db/operate';
import log from '@feidao/web/atom/nodejs/logger/log';

interface Message {
	systemid1: string;
	systemid2: string;
	// todo
	[field: string]: any;
}

interface Star {
	name: string;
	sex: 0 | 1;
}

interface FruitPrices {
	name: string;
	price: number;
}

interface Hobby {
	star: string;
	hobby: string;
}
interface Works {
	star: string;
	works: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const { systemid1, systemid2 } = msg;
	const { exec, insert, update, del } = operate(action_id, session_id, spaceid, systemid1);
	// #region 插入数据
	// 先插入一条数据
	const fruitid = insert('fruitprices', { name: '番茄', price: 0.5 });
	// 因为这里下面这
	const star_id = insert('star', { name: '悟能', sex: 1 });
	insert('hobby', { star: star_id, hobby: '吃和睡' });
	// #endregion 插入数据
	// #region 修改数据
	update('fruitprices', {
		_id: fruitid
	}, { name: '番茄', price: 1.5 });
	// 注意，这里没有传name字段
	update('fruitprices', {
		_id: fruitid
	}, { price: 5.5 });
	// #endregion 修改数据
	const ret = await exec();
	if (ret.code !== 1) {
		return 'fail';
	}
	// 下面是另外一个库的操作，所以，需要分开，如果是同一个库，则无须分开
	const { exec: exec2, insert: insert2 } = operate(action_id, session_id, spaceid, systemid2);
	// #region 插入多条数据
	// 同一个表插入多条数据
	insert2('works', { star: star_id, works: '九吃钉耙' });
	insert2('works', { star: star_id, works: '嫦娥仙子' });
	// #endregion 插入多条数据
	// #region 删除数据
	del('works', { star: star_id });
	// #endregion 删除数据
	const ret2 = await exec2();
	log('finish');
	if (ret2.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
